package com.supereasy.kotlincor

import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.supereasy.kotlincor.http.MyUrl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

class BaseCoroutineActivity : AppCompatActivity() {

    val mainScope = MainScope()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_base_coroutine)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        mainScope.launch {
            val result = withContext(Dispatchers.IO) { getResult() }
            findViewById<TextView>(R.id.base_text).text = result
        }
//
//        mainScope.launch(Dispatchers.IO) {
//            val result = getResult()
//            withContext(Dispatchers.Main) {
//                findViewById<TextView>(R.id.base_text).text = result
//            }
//        }

    }


    private suspend fun getResult(): String? {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(MyUrl.url)
            .build()
        val response = client.newCall(request).execute()
        return response.body?.string()
    }

    override fun onDestroy() {
        super.onDestroy()
        mainScope.cancel()
    }
}